<template>
  <div class="dashboard-container">
    <div class="app-container">
    <el-card shadow="never">
      <el-row type="flex" justify="space-between" style="margin-bottom: 15px">
        <span style="font-size: 12px; color: pink">说明：目前支持学科和关键字条件筛选</span>
        <el-button type="success" icon="el-icon-edit" style="font-size: 12px" @click="$router.push('/questions/new')">新增试题</el-button>
      </el-row>
      <!-- 搜索栏组件 -->
      <questionForm @searchQuestion="searchQuestion" @clearSearch="clearSearch"></questionForm>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-alert
          :title="`数据一共${counts}条`"
          type="info"
          show-icon
          :closable="false"/>
        <el-tab-pane label="全部" name="first"/>
        <el-tab-pane label="待审核" name="second"/>
        <el-tab-pane label="已审核" name="third"/>
        <el-tab-pane label="已拒绝" name="fourth"/>
      </el-tabs>
      <el-table :data="tableData" style="width: 100%; margin-top: 20px">
        <el-table-column
          prop="number"
          label="试题编号"/>
        <el-table-column
          prop="subject"
          label="学科"/>
        <el-table-column
          prop="catalog"
          label="目录"/>
        <el-table-column
          prop="questionType"
          :formatter="formatQuestionType"
          label="题型"/>
        <el-table-column prop="question" label="题干">
          <template v-slot="{ row }">
            {{ row.question | html2Text }}
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间">
          <template v-slot="{ row }">
            {{ row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column
          prop="difficulty"
          label="难度"
          :formatter="formatDifficulty"/>
        <el-table-column
          prop="creator"
          label="录入人"/>
        <el-table-column
          prop="chkState"
          :formatter="formatChkType"
          label="审核状态"/>
        <el-table-column
          prop="chkRemarks"
          label="审核意见"/>
        <el-table-column
          prop="chkUser"
          label="审核人"/>
        <el-table-column
          prop="publishState"
          :formatter="formatPublishState"
          label="发布状态"/>
        <el-table-column
          fixed="right"
          prop="date"
          label="操作"
          width="200"
          align="center">
          <template v-slot="{ row }">

            <el-button type="text" @click="showQuestionDetail(row.id)"
              >预览</el-button>
            <el-button v-Audit="row" type="text" @click="showReviewComments(row)">审核</el-button>
            <el-button v-disable="row" type="text" @click="revise(row)">修改</el-button>
            <el-button v-Shelves="row" type="text" @click="publish(row)">{{row.publishState===1?'下架':'上架'}} </el-button>
            <el-button v-disable="row" type="text"  @click="delQuestion(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" justify="end">
        <el-pagination
          background
          layout="prev, pager, next ,sizes ,jumper"
          :total="counts"
          style="margin-top: 20px"
          :page-sizes="[5, 10, 20, 50]"
          :current-page.sync="params.page"
          :page-size.sync="params.pagesize"
          @size-change="getChoiceList()"
          @current-change="getChoiceList()"/>
      </el-row>
      <!-- 预览弹窗 -->
      <questionDialog
        :showQuestionDialog.sync="showQuestionDialog"
        ref="questionDialog"/>
      <!-- 审核弹窗 -->
      <el-dialog :visible="showAudit" title="题目审核" width="25%" :before-close="btnCancel">
        <el-form :model="formData" :rules="rules" ref="formdialog">
          <el-form-item>
            <el-radio-group v-model="formData.radio">
            <el-radio label='1'>通过</el-radio>
            <el-radio label='2'>拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="textarea">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入审核意见"
              v-model="formData.textarea"/>
          </el-form-item>
         <el-row type="flex" justify="end">
           <el-form-item>
            <el-button @click="btnCancel">取消</el-button>
            <el-button type="primary" @click="choiceCheck">确认</el-button>
          </el-form-item>
         </el-row>
        </el-form>
      </el-dialog>
    </el-card>
    </div>
  </div>
</template>

<script>
import questionDialog from '@/module-hmmm/components/question-dialog'
import questionForm from '@/module-hmmm/components/question-form'
import {
  questionType,
  difficulty,
  chkType
} from '@/api/hmmm/constants'
import { choice, choiceCheck, remove as delQuestion, choicePublish } from '@/api/hmmm/questions.js'

const btnDisable = (dom) => {
  dom.disabled = true
  dom.classList.add('is-disabled')
}
const btnRelieve = (dom) => {
  dom.disabled = false
  dom.classList.remove('is-disabled')
}
export default {
  components: {
    questionDialog,
    questionForm
  },
  data () {
    return {
      activeName: 'first',
      tableData: [],
      counts: 0,
      params: {
        page: 1,
        pagesize: 5
      },
      showQuestionDialog: false,
      showAudit: false,

      questionDetail: {},
      formData: {
        radio: '2',
        textarea: ''
      },
      rules: {
        textarea: [
          { required: true, message: '请填写审核建议', trigger: 'blur' }
        ]
      }
    }
  },
  // 切换tab栏
  methods: {
    // 获取题库列表
    async getChoiceList (searchData = {}) {
      const { data } = await choice({ ...this.params, ...searchData })
      this.counts = data.counts
      this.tableData = data.items
      return this.tableData
    },
    // 筛选出chkType
    async handleClick (tab) {
      this.tableData = await this.getChoiceList()
      if (tab.index === '0') {
        this.getChoiceList()
      } else {
        const res = this.tableData.filter(
          (item) => item.chkState === (Number(tab.index) - 1)
        )
        this.tableData = [...res]
      }
    },
    // 格式化题型
    formatQuestionType (row) {
      const res = questionType.find(
        (item) => item.value === Number(row.questionType)
      )
      return res?.label ? res.label : '未知'
    },
    // 格式化难度
    formatDifficulty (row) {
      const res = difficulty.find(
        (item) => item.value === Number(row.difficulty)
      )
      return res?.label ? res.label : '未知'
    },
    // 格式化审核状态
    formatChkType (row) {
      const res = chkType.find((item) => item.value === Number(row.chkState))

      return res?.label ? res.label : '待审核'
    },
    // 格式化发布状态
    formatPublishState (row) {
      if (row.chkState === 1 && row.publishState === 1) {
        return '已发布'
      } else if (row.chkState === 2 && row.publishState === 0) {
        return '已下架'
      } else {
        return '待发布'
      }
    },
    // 精选题库预览
    async showQuestionDetail (id) {
      await this.$refs.questionDialog.getQuestionDetail(id)
      this.showQuestionDialog = true
    },
    // 审核意见
    showReviewComments (row) {
      this.showAudit = true
      this.questionDetail = row
    },
    // 上传试题审核意见
    async choiceCheck () {
      try {
        // 手动校验
        await this.$refs.formdialog.validate()
        // 更改对应项的值
        this.questionDetail.chkRemarks = this.formData.textarea
        this.questionDetail.chkState = Number(this.formData.radio)
        // 发起请求
        await choiceCheck(this.questionDetail)
        // 刷新页面数据
        this.getChoiceList()
        // 退出页面
        this.btnCancel()
        this.$message.success('审核成功！')
      } catch {
        this.$message.error('审核失败!')
      }
    },
    // 审核取消
    btnCancel () {
      // 重置表单数据
      this.formData = {
        radio: '2',
        textarea: ''
      }
      // 清空校验规则
      this.$refs.formdialog.clearValidate()
      this.showAudit = false
    },
    // 修改按钮
    revise (row) {
      // 跳转路由
      this.$router.push({ path: '/questions/new', query: { id: `${row.id}` } })
    },
    // 删除按钮
    async delQuestion (row) {
      try {
        // 提示是否删除
        await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 发起请求
        await delQuestion({ id: row.id })
        const totalPage = Math.ceil((this.counts - 1) / this.params.pagesize)
        if (this.params.page > totalPage) {
          this.params.page = totalPage
        }
        this.getChoiceList()
        this.$message.success('删除成功！！！')
      } catch {
        this.$message('您已取消删除')
      }
    },
    // 发布与待发布
    async publish (row) {
      try {
        if (row.publishState === 0) {
          await this.$confirm('您确定上架这道题目吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          row.publishState = 1
        } else if (row.publishState === 1) {
          await this.$confirm('您确定下架这道题目吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          row.publishState = 0
        }
        await choicePublish(row)
        this.getChoiceList()
        this.$message.success(row.publishState === 1 ? '上架成功！！' : '下架成功！！')
      } catch {
        this.$message('您已取消题目操作')
      }
    },
    // 搜索按钮
    searchQuestion (data) {
      this.getChoiceList(data)
    },
    // 清除搜索
    clearSearch () {
      this.getChoiceList()
    }

  },
  created () {
    this.getChoiceList()
  },
  // 自定义指令
  directives: {
    // 审核按钮禁用
    Audit: {
      inserted (dom, options) {
        if (options.value.chkState === 1 || options.value.chkState === 2) {
          btnDisable(dom)
        }
        if (options.value.chkState === 0) {
          btnRelieve(dom)
        }
      },
      componentUpdated (dom, options) {
        if (options.value.chkState === 1 || options.value.chkState === 2) {
          btnDisable(dom)
        }
        if (options.value.chkState === 0) {
          btnRelieve(dom)
        }
      }
    },

    disable: {
      inserted (dom, options) {
        if (options.value.publishState === 1) {
          btnDisable(dom)
        }
        if (options.value.publishState !== 1) {
          btnRelieve(dom)
        }
      },
      componentUpdated (dom, options) {
        if (options.value.publishState === 1 && options.value.chkState === 1) {
          btnDisable(dom)
        }
        if (options.value.publishState !== 1) {
          btnRelieve(dom)
        }
      }
    },
    Shelves: {
      inserted (dom, options) {
        if (options.value.chkState !== 1) {
          btnDisable(dom)
        }
        if (options.value.chkState === 1) {
          btnRelieve(dom)
        }
      },
      componentUpdated (dom, options) {
        if (options.value.chkState !== 1) {
          btnDisable(dom)
        }
        if (options.value.chkState === 1) {
          btnRelieve(dom)
        }
      }
    }
  }
}
</script>

<style scoped>
.el-tabs__item.is-active {
  border-bottom: 1px solid #e4e7ed;
}
/* .operate{
font-size: 12px;
} */
.el-button--medium {
  font-size: 12px;
}
</style>
